<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>02-相机运动</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    html,
    body {
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <script type="module">
    import * as THREE from "three";
    // 创建场景
    const scene = new THREE.Scene();

    // 贴图
    const loader = new THREE.TextureLoader();
    loader.load("../images/01.jpg", function(texture) {
      scene.background = texture;
      // 因为load函数是异步的， 这个回调函数里需要手动渲染一次。但是我们这里使用了animate，所以不需要再渲染一次
      // renderer.render(scene, camera);
    });

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      45, 
      window.innerWidth / window.innerHeight, 
      1, 
      1000
    );
    camera.position.set(0, 20, 10);
    camera.lookAt(0, 0, 0);

    // 创建渲染器 
    const renderer = new THREE.WebGLRenderer();
    // 设置渲染器大小
    renderer.setSize(window.innerWidth, window.innerHeight);
    // 把渲染的canvas内容添加到body
    document.body.appendChild(renderer.domElement);

    // 创建一个物体
    const cube = new THREE.Mesh(
      new THREE.BoxGeometry(4, 4, 4),
      new THREE.MeshBasicMaterial({
        color: "yellow"
      })
    );
    const cube2 = new THREE.Mesh(
      new THREE.SphereGeometry(),
      new THREE.MeshBasicMaterial({
        color: 0xff0000
      })
    );

    cube2.position.x = 5;
    // 把物体添加到场景中
    scene.add(cube, cube2);

    let angle = 0;

    function animate() { 
      cube.rotation.x += 0.01;
      cube.rotation.y += 0.01;

      const radius = 3; // 半径

      angle += 0.01;
      camera.position.x = radius * Math.cos(angle);
      camera.position.z = radius * Math.sin(angle);
      camera.lookAt(0, 0, 0);
      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }

    // 添加动画并渲染
    animate();

    // 监听屏幕变化
    window.addEventListener("resize", function () {
      // 更新摄像头
      camera.aspect = window.innerWidth / window.innerHeight;
      // 更新摄像机的投影矩阵
      camera.updateProjectionMatrix();
      // 更新渲染器
      renderer.setSize(window.innerWidth, window.innerHeight);
      // 设置渲染器的像素比
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.render(scene, camera);
    });
  </script>
</body>
</html>